import time
from time import sleep

from appium import webdriver
from selenium.webdriver.common.by import By


class Test_app():
    def setup_class(self):
        desired_caps = dict()
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '7.1.2'
        desired_caps['deviceName'] = 'emulator-5554'
        desired_caps['appPackage'] = 'com.android.settings'
        desired_caps['appActivity'] = '.Settings'
        desired_caps['unicodeKeyboard'] = True
        desired_caps['resetKeyboard'] = True
        self.desired_caps = desired_caps
    def test_hello(self):

        driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)
        sleep(3)
        driver.quit()

    def test_1(self):
        driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)
        sleep(3)
        #com.baidu.homework/.activity.index.IndexActivity
        driver.start_activity("com.baidu.homework","activity.index.IndexActivity")
        #获取包名和界面名
        print("包名",driver.current_package)
        print("界面名",driver.current_activity)

        time.sleep(2)
        driver.quit()

    def test_2(self):
        driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)
        # sleep(3)
        #卸载作业帮，(com.baidu.homework 包名)
        # driver.remove_app("com.baidu.homework")
        #安装作业帮
        driver.install_app("D:\zuoyebang.apk")
        driver.quit()

    def test_3(self):
        """apph后台运行
            截图
        """
        self.desired_caps['appPackage'] = 'com.baidu.homework'
        self.desired_caps['appActivity'] = 'activity.index.IndexActivity'
        driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)

        sleep(2)
        driver.background_app(10)  # 后台运行
        # #获取当前页面截图的字节数据
        # png = driver.get_screenshot_as_png()
        # #创建文件，并将截图的字节数据写入(数据为二进制:b)
        # open("a1.png",mode="wb").write(png)

        bs2 = driver.get_screenshot_as_png()  # 获取截图的字节数据

        str_time = time.strftime("%Y%m%d-%H%M%S", time.localtime())  #获取时间

        open(f"{str_time}.png", mode="wb").write(bs2)  # 创建文件， 并将截图的字节数据写入

    def test_4(self):
        driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)
        # sleep(3)
        # driver.find_element(By.ID,value='com.android.settings:id/search').click()
        # time.sleep(3)

        driver.find_element(By.ID, value="com.android.settings:id/search").click()
        sleep(2)
        driver.find_element(By.CLASS_NAME, value="android.widget.EditText").send_keys("hello").clear().send_keys("多少度")

        sleep(2)
        driver.find_element(By.XPATH, value="//*[@class='android.widget.ImageButton']").click()
        sleep(2)
        driver.quit()
